<template>
    <div class="payment-records">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>支付记录</span>
                </div>
            </template>
            
            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>
            
            <div v-else>
                <!-- 角色类型信息（开发时查看，可以后续删除） -->
                <div class="role-info" style="margin-bottom: 10px; color: #999;">
                    当前角色: {{ isTeacher ? '教师' : '学生' }} ({{ tokenStore.userRole }})
                </div>
                
                <!-- 标签页 -->
                <div class="filter-tabs">
                    <el-tabs v-model="activeTab">
                        <el-tab-pane v-if="!isTeacher" label="我的支付" name="student"></el-tab-pane>
                        <el-tab-pane v-if="isTeacher" label="收款记录" name="teacher"></el-tab-pane>
                    </el-tabs>
                </div>
                
                <div v-if="records.length === 0" class="empty-records">
                    <el-empty description="暂无支付记录" />
                </div>
                
                <el-table v-else :data="records" style="width: 100%">
                    <el-table-column prop="orderNo" label="订单编号" width="180" />
                    <el-table-column prop="tutoringTitle" label="课程名称" />
                    
                    <el-table-column v-if="isStudent" prop="teacherName" label="教师姓名" />
                    <el-table-column v-if="isTeacher" prop="studentName" label="学生姓名" />
                    
                    <el-table-column prop="amount" label="金额">
                        <template #default="scope">
                            ¥{{ scope.row.amount }}
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="支付状态">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="创建时间">
                        <template #default="scope">
                            {{ formatDateTime(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="操作" width="180">
                        <template #default="scope">
                            <el-button 
                                v-if="isStudent && scope.row.status === 0"
                                type="primary" 
                                size="small" 
                                @click="goToPay(scope.row)"
                            >
                                去支付
                            </el-button>
                            <el-button 
                                v-if="scope.row.status === 0"
                                type="warning" 
                                size="small" 
                                @click="manualUpdateStatus(scope.row)"
                            >
                                更新状态
                            </el-button>
                            <el-button 
                                type="info" 
                                size="small" 
                                @click="showDetail(scope.row)"
                            >
                                详情
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
        
        <!-- 订单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="订单详情" width="500px">
            <div v-if="currentOrder" class="order-detail">
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
                    <el-descriptions-item label="课程名称">{{ currentOrder.tutoringTitle }}</el-descriptions-item>
                    <el-descriptions-item v-if="isStudent" label="教师姓名">{{ currentOrder.teacherName }}</el-descriptions-item>
                    <el-descriptions-item v-if="isTeacher" label="学生姓名">{{ currentOrder.studentName }}</el-descriptions-item>
                    <el-descriptions-item label="支付金额">¥{{ currentOrder.amount }}</el-descriptions-item>
                    <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod === 'alipay' ? '支付宝' : currentOrder.paymentMethod }}</el-descriptions-item>
                    <el-descriptions-item label="支付状态">
                        <el-tag :type="getStatusType(currentOrder.status)">
                            {{ getStatusText(currentOrder.status) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="currentOrder.tradeNo" label="支付宝交易号">{{ currentOrder.tradeNo }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ formatDateTime(currentOrder.createTime) }}</el-descriptions-item>
                </el-descriptions>
                
                <div v-if="currentOrder.status === 0" class="dialog-footer mt-3">
                    <el-button v-if="isStudent" type="primary" @click="goToPay(currentOrder)">去支付</el-button>
                    <el-button type="warning" @click="manualUpdateStatus(currentOrder)">更新状态</el-button>
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </div>
                <div v-else class="dialog-footer mt-3">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { paymentService } from '@/api/payment'
import { formatDateTime } from '@/utils/format'
import { useTokenStore } from '@/stores/token.js'

const router = useRouter()
const tokenStore = useTokenStore()
const loading = ref(true)
const records = ref([])
const activeTab = ref('student')
const detailDialogVisible = ref(false)
const currentOrder = ref(null)

// 使用token store获取用户角色
const userRole = computed(() => tokenStore.userRole)
console.log('Records组件初始化 - token store用户角色:', tokenStore.userRole)

// 计算属性
const isStudent = computed(() => Number(userRole.value) === 0)
const isTeacher = computed(() => Number(userRole.value) === 1)

// 获取支付状态类型
const getStatusType = (status) => {
    switch (status) {
        case 0: return 'warning'  // 未支付
        case 1: return 'success'  // 支付成功
        case 2: return 'danger'   // 支付失败
        default: return 'info'
    }
}

// 获取支付状态文本
const getStatusText = (status) => {
    switch (status) {
        case 0: return '未支付'
        case 1: return '支付成功'
        case 2: return '支付失败'
        default: return '未知状态'
    }
}

// 获取支付记录
const getRecords = async () => {
    loading.value = true
    try {
        let response
        // 首先确认角色，设置正确的标签页和API调用
        if (isTeacher.value) {
            activeTab.value = 'teacher'
            console.log('教师角色：获取收款记录')
            response = await paymentService.getTeacherPayments()
        } else {
            activeTab.value = 'student'
            console.log('学生角色：获取支付记录')
            response = await paymentService.getStudentPayments()
        }
        
        if (response && response.data) {
            records.value = response.data
            console.log(`成功获取${records.value.length}条记录`)
        } else {
            records.value = []
            console.log('未获取到记录数据')
        }
    } catch (e) {
        console.error('获取支付记录失败:', e)
        ElMessage.error(e.response?.data?.message || '获取支付记录失败')
        records.value = []
    } finally {
        loading.value = false
    }
}

// 去支付
const goToPay = (order) => {
    if (!order || !order.orderNo) {
        ElMessage.error('无效的订单信息')
        return
    }
    
    // 关闭详情对话框
    detailDialogVisible.value = false
    
    // 跳转到支付页面
    router.push(`/payment/create?orderNo=${order.orderNo}`)
}

// 手动更新支付状态（临时解决方案）
const manualUpdateStatus = async (order) => {
    if (!order || !order.orderNo) {
        ElMessage.error('无效的订单信息')
        return
    }
    
    try {
        // 确认操作
        await ElMessageBox.confirm(
            '确定将此订单标记为已支付吗？这是因为支付宝回调可能在本地开发环境无法正常工作。',
            '手动更新支付状态',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        // 调用API更新状态
        const response = await paymentService.manualUpdatePaymentStatus(order.orderNo)
        
        if (response.code === 0) {
            ElMessage.success('订单状态已更新为已支付')
            // 重新加载订单列表
            getRecords()
        } else {
            ElMessage.error(response.message || '更新订单状态失败')
        }
    } catch (e) {
        if (e !== 'cancel') {
            console.error('手动更新订单状态失败:', e)
            ElMessage.error(e.response?.data?.message || '更新订单状态失败')
        }
    }
}

// 显示订单详情
const showDetail = (order) => {
    currentOrder.value = order
    detailDialogVisible.value = true
}

// 监听标签页变化
watch(activeTab, (newVal) => {
    getRecords()
})

// 设置初始标签页
onMounted(() => {
    console.log('Records组件挂载 - token store用户角色:', tokenStore.userRole)
    console.log('Records组件挂载 - isStudent:', isStudent.value)
    console.log('Records组件挂载 - isTeacher:', isTeacher.value)
    
    // 根据用户角色设置默认标签页
    if (isTeacher.value) {
        console.log('设置教师默认标签页 - 用户角色为教师(1)')
        activeTab.value = 'teacher'
    } else {
        console.log('设置学生默认标签页 - 用户角色为:', tokenStore.userRole)
        activeTab.value = 'student'
    }
    
    getRecords()
})
</script>

<style scoped>
.payment-records {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.loading-container, .empty-records {
    padding: 20px;
}

.filter-tabs {
    margin-bottom: 20px;
}

.order-detail {
    padding: 10px;
}

.mt-3 {
    margin-top: 15px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style> 